import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, 
    QStackedWidget, QLabel, QHBoxLayout
)

class DynamicWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.content_widget = QWidget()  # 内容容器
        self.init_ui()
        self.load_interface_a()  # 初始化默认界面

    def init_ui(self):
        main_layout = QHBoxLayout()  # 使用水平布局管理按钮
        
        # 切换按钮
        btn_layout = QVBoxLayout()  # 按钮垂直排列
        btn_a = QPushButton("加载界面A", clicked=self.load_interface_a)
        btn_b = QPushButton("加载界面B", clicked=self.load_interface_b)
        btn_layout.addWidget(btn_a)
        btn_layout.addWidget(btn_b)
        
        # 主布局组合
        main_layout.addLayout(btn_layout)
        main_layout.addWidget(self.content_widget)
        self.setLayout(main_layout)

    def load_interface_a(self):
        self._clear_layout()
        layout = QVBoxLayout()
        layout.addWidget(QLabel("这是动态加载的界面A"))
        self.content_widget.setLayout(layout)
        self.content_widget.update()  # 强制界面刷新[1](@ref)

    def load_interface_b(self):
        self._clear_layout()
        layout = QVBoxLayout()
        layout.addWidget(QPushButton("动态按钮"))
        self.content_widget.setLayout(layout)
        self.content_widget.update()  # 强制界面刷新[1](@ref)

    def _clear_layout(self):
        if self.content_widget.layout():  # 检查布局是否存在[2](@ref)
            while self.content_widget.layout().count():
                item = self.content_widget.layout().takeAt(0)
                if item.widget():
                    item.widget().deleteLater()  # 安全删除控件

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DynamicWindow()
    window.setWindowTitle("动态布局示例")
    window.show()
    sys.exit(app.exec())